package com.examsystem.util;

import com.examsystem.config.DynamicTaskService;
import com.examsystem.pojo.vo.PaperClassVo;
import com.examsystem.service.PaperService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;

import java.util.Date;
import java.util.Hashtable;
import java.util.Set;

/**
 * @author Administrator
 */
public class Handler implements Runnable {
    private Hashtable<String, PaperClassVo> paperMap = new Hashtable();
    @Autowired
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
    @Autowired
    private PaperService paperService;
    @Autowired
    private DynamicTaskService dynamicTaskService;


    @Autowired
    private PaperClassVo paperClassVo;
    private int studentId;

    public Handler(PaperClassVo paperClassVo, int studentId) {
        this.paperClassVo = paperClassVo;
        this.studentId = studentId;
    }

    @Override
    public void run() {
        String begin = new Date().toLocaleString();
        Set keys = paperMap.keySet();
        for (Object key : keys) {
            PaperClassVo paper = paperMap.get(key);
            if (paper == null) {
                paperMap.remove(key);
                continue;
            }
            //计算结束时间(在原来基础上加5秒钟)
            //long sotpTime = paper.getBeginTime().getTime() + paper.getTime() * 60 * 1000l + 5000;
            DataUtil dataUtil = new DataUtil();
            String end = dataUtil.changeTime(begin, paper.getExamTime());
            boolean b = dataUtil.checkTime(begin, end);
            if (!b) {
                //时间结束调用交卷方法
                try {
                    paperService.putInPaper(paper.getPaper().getPaperId(),1, paper.getPcClass());
                    System.out.println("执行交卷" + new Date().toLocaleString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                //移除数据
                paperMap.remove(key);
            }
        }
        if (paperMap.size() == 0) {
            //停止轮询
            dynamicTaskService.stopCron();
        }
    }
}